<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */

namespace MoChat\App\Client\Action\Dashboard;

use _PHPStan_b8e553790\Nette\Neon\Exception;
use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\App\Rbac\Middleware\PermissionMiddleware;
use MoChat\App\Client\Logic\IndexLogic;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;

/**
 * 客户标签组删除
 * @Controller
 */
class ClientGroupLabelDel extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class)
     * })
     * @RequestMapping(path="/dashboard/client/groupLabelDel", methods="DELETE")
     */
    public function handle()
    {
        $user = user();
        if (empty($user)) {
            throw new CommonException(ErrorCode::AUTH_UNAUTHORIZED, '登入异常请重新登入');
        }
        $data = $this->request->all();
        Db::beginTransaction();
        try {
            $labelIds = Db::table('client_label')
                ->where('client_label_group_id', $data['id'])
                ->pluck('id');
            $labelIds || $labelIds = collect([]);
            $labelIds = $labelIds->toArray();
            $has = Db::table('client_label_relation')
                ->whereIn('client_label_id', $labelIds)
                ->get();
            $has || $has = collect([]);
            $has = $has->toArray();
            if (!empty($has)) {
                throw new CommonException(ErrorCode::SERVER_ERROR, '分组下的标签已经使用，请先删除客户标签关系');
            }
            Db::table('client_label_group')
                ->where('id', $data['id'])
                ->delete();
            Db::table('client_label')
                ->where('client_label_group_id', $data['id'])
                ->delete();
            Db::commit();
        } catch (\Throwable $throwable) {
            Db::rollBack();
            throw new CommonException(ErrorCode::SERVER_ERROR, $throwable->getMessage());
        }
        return [];
    }

    /**
     * 验证规则.
     *
     * @return array 响应数据
     */
    public function rules(): array
    {
        return [
            'id' => 'required',
        ];
    }

    /**
     * 获取已定义验证规则的错误消息.
     */
    public function messages(): array
    {
        return [
            'id.required' => '分组id必传',
        ];
    }
}
